package com.dony.web.controller.order;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dony.common.core.controller.BaseController;
import com.dony.common.core.domain.AjaxResult;
import com.dony.common.core.page.TableDataInfo;
import com.dony.common.utils.DateUtils;
import com.dony.order.domain.Order;
import com.dony.order.domain.PurchaseRecord;
import com.dony.order.domain.vo.OrderPackVo;
import com.dony.order.service.*;
import com.dony.shop.domain.Supplier;
import com.dony.shop.service.ISupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author sundw
 * @version 1.0.0
 * @description ProductController
 * @since 2023/2/23 18:42
 */
@Slf4j
@RestController
@RequestMapping("/shopee/order/pack")
public class OrderPackController extends BaseController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderPackService orderPackService;
    @Autowired
    ILogisticsService logisticsService;
    @Autowired
    private IPurchaseRecordService purchaseRecordService;
    @Autowired
    private ISupplierService supplierService;
    @Autowired
    private IOperationRecordService operationService;
    @Autowired
    private IBlackRecordService blackRecordService;
    @Resource
    ThreadPoolTaskExecutor executor;


    /**
     * 采购
     */
    @PostMapping(value = "/purchase/{orderSns}")
    public AjaxResult purchase(@PathVariable("orderSns") String[] orderSns,
                               @RequestParam(value = "supplierId", required = false) Long supplierId) {
        //获取供应商
        Supplier supplier = supplierService.getById(supplierId);
        List<PurchaseRecord> records = Arrays.stream(orderSns).map(sn -> {
            //生成包裹
            Order order = orderService.getById(sn);
            executor.execute(() -> {
                boolean shipped = logisticsService.shipOrder(order.getShopId(), sn);
                if (!shipped) {
                    log.error("订单生成包裹失败！订单号：" + sn);
                }
            });
            PurchaseRecord record = new PurchaseRecord();
            record.setOrderSn(sn);
            if (supplier != null) {
                record.setSupplierId(supplierId);
                record.setSupplierName(supplier.getName());
            }
            record.setCreateTime(DateUtils.getNowDate());
            record.setCreateBy(getUsername());
            record.setDelFlat("0");

            //保存操作记录
            operationService.addRecord(sn, "采购", supplier == null ? null : "采购商：" + supplier.getName());

            return record;
        }).collect(Collectors.toList());
        purchaseRecordService.saveBatch(records);
        //更新订单状态
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("sys_status", 2);
        // 使用in条件匹配orderSns集合中的订单号
        updateWrapper.in("order_sn", orderSns);
        // 执行批量更新操作
        orderService.update(updateWrapper);
        return AjaxResult.success();
    }


    /**
     * 提交
     */
    @PostMapping("/submit/{orderSns}")
    public AjaxResult submit(@PathVariable("orderSns") String[] orderSns) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        //设置打包时间
        updateWrapper.set("operation_time", DateUtils.getNowDate());
        updateWrapper.set("sys_status", 3).in("order_sn", orderSns);
        //添加操作记录
        for (String orderSn : orderSns) {
            operationService.addRecord(orderSn, "打包", null);
        }
        return toAjax(orderService.update(updateWrapper));
    }

    /**
     * 回退
     */
    @PostMapping("/back/{orderSns}")
    public AjaxResult back(@PathVariable("orderSns") String[] orderSns) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("sys_status", 2).in("order_sn", orderSns);
        //添加操作记录
        for (String orderSn : orderSns) {
            operationService.addRecord(orderSn, "回退", null);
        }
        return toAjax(orderService.update(updateWrapper));
    }

    /**
     * 完结
     */
    @PostMapping("/finish/{orderSns}")
    public AjaxResult finish(@PathVariable("orderSns") String[] orderSns) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("sys_status", 6).in("order_sn", orderSns);
        for (String orderSn : orderSns) {
            operationService.addRecord(orderSn, "完成", null);
        }
        return toAjax(orderService.update(updateWrapper));
    }

    /**
     * 批量完结
     */
    @PostMapping("/outs/{orderSns}")
    public AjaxResult outs(@PathVariable("orderSns") String[] orderSns) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("sys_status", 4).in("order_sn", orderSns);
        for (String orderSn : orderSns) {
            operationService.addRecord(orderSn, "缺货", null);
        }
        return toAjax(orderService.update(updateWrapper));
    }


    /**
     * 缺货
     */
    @PostMapping("/out")
    public AjaxResult out(@RequestBody Order order) {
        operationService.addRecord(order.getOrderSn(), "缺货", order.getSysNote());
        return toAjax(orderService.updateById(order));
    }


    /**
     * 加急
     */
    @PostMapping("/emergency")
    public AjaxResult emergency(@RequestBody Order order) {
        //操作加急
        operationService.addRecord(order.getOrderSn(), order.getEmergency() ? "加急" : "取消加急", null);
        //取消加急设置为null
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("emergency", order.getEmergency() ? order.getEmergency() : null);
        updateWrapper.eq("order_sn",order.getOrderSn());
        return toAjax(orderService.update(updateWrapper));
    }

    /**
     * 备注
     */
    @PostMapping("/remark")
    public AjaxResult remark(@RequestBody Order order) {
        operationService.addRecord(order.getOrderSn(), "备注", order.getSysNote());
        return toAjax(orderService.updateById(order));
    }

    /**
     * 拉黑
     */
    @PostMapping("/black")
    public AjaxResult black(@RequestBody Order order) {
        //添加黑名单记录
        blackRecordService.blackOrder(order.getOrderSn(), order.getBlack());
        operationService.addRecord(order.getOrderSn(), order.getBlack() ? "拉黑" : "取消拉黑", null);
        return toAjax(orderService.updateById(order));
    }


}
